<template>
  <div class="permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button 
            v-has-role="'admin'" 
            type="primary" 
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <mobile-search
        :search-form="searchForm"
        @search="handleSearch"
        @reset="handleReset"
      >
        <template #default="{ searchForm }">
          <el-form-item label="权限名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入权限名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="权限类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择权限类型"
              clearable
            >
              <el-option label="菜单权限" value="menu" />
              <el-option label="按钮权限" value="button" />
              <el-option label="数据权限" value="data" />
            </el-select>
          </el-form-item>
        </template>
      </mobile-search>

      <!-- 表格区域 -->
      <mobile-table
        :data="tableData"
        :current-page="pagination.page"
        :page-size="pagination.size"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
        <!-- 桌面端表格 -->
        <template #desktop-table>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="code" label="权限编码" />
            <el-table-column prop="type" label="权限类型">
              <template #default="{ row }">
                <el-tag :type="getTypeColor(row.type)">
                  {{ getTypeName(row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="resource" label="资源路径" />
            <el-table-column prop="method" label="请求方法">
              <template #default="{ row }">
                <el-tag v-if="row.method" size="small" :type="getMethodColor(row.method)">
                  {{ row.method }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="status" label="状态">
              <template #default="{ row }">
                <el-switch
                  v-model="row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="{ row }">
                <el-button
                  v-has-role="'admin'"
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-has-role="'admin'"
                  type="success"
                  size="small"
                  @click="handleAddChild(row)"
                >
                  新增子权限
                </el-button>
                <el-button
                  v-has-role="'admin'"
                  type="danger"
                  size="small"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>

        <!-- 移动端卡片 -->
        <template #mobile-card="{ row }">
          <div class="permission-card">
            <div class="permission-header">
              <div class="permission-info">
                <h3>{{ row.name }}</h3>
                <p class="permission-code">{{ row.code }}</p>
              </div>
              <div class="permission-tags">
                <el-tag :type="getTypeColor(row.type)" size="small">
                  {{ getTypeName(row.type) }}
                </el-tag>
                <el-tag v-if="row.method" size="small" :type="getMethodColor(row.method)">
                  {{ row.method }}
                </el-tag>
              </div>
            </div>

            <div class="permission-details">
              <div class="detail-item" v-if="row.resource">
                <span class="label">资源路径：</span>
                <span class="value">{{ row.resource }}</span>
              </div>
              <div class="detail-item" v-if="row.description">
                <span class="label">描述：</span>
                <span class="value">{{ row.description }}</span>
              </div>
            </div>

            <div class="permission-actions">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
                style="margin-right: 12px;"
              />
              <el-button
                v-has-role="'admin'"
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                v-has-role="'admin'"
                type="success"
                size="small"
                @click="handleAddChild(row)"
              >
                新增
              </el-button>
              <el-button
                v-has-role="'admin'"
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </mobile-table>


    </el-card>

    <!-- 权限表单对话框 -->
    <mobile-form
      v-model="dialogVisible"
      :title="dialogTitle"
      :loading="submitLoading"
      @confirm="handleSubmit"
      @close="handleDialogClose"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
      >
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissionTreeData"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            placeholder="请选择上级权限"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码，如：user:add" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单权限" value="menu" />
            <el-option label="按钮权限" value="button" />
            <el-option label="数据权限" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源路径" prop="resource">
          <el-input v-model="permissionForm.resource" placeholder="请输入资源路径，如：/api/users" />
        </el-form-item>
        <el-form-item label="请求方法" prop="method">
          <el-select v-model="permissionForm.method" placeholder="请选择请求方法" clearable>
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="PATCH" value="PATCH" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionForm.sort" :min="0" />
        </el-form-item>
      </el-form>
    </mobile-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MobileTable from '@/components/MobileTable/index.vue'
import MobileForm from '@/components/MobileForm/index.vue'
import MobileSearch from '@/components/MobileSearch/index.vue'

const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const permissionFormRef = ref()

const searchForm = reactive({
  name: '',
  type: ''
})

const permissionForm = reactive({
  id: null,
  parentId: null,
  name: '',
  code: '',
  type: 'menu',
  resource: '',
  method: '',
  description: '',
  sort: 0
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const tableData = ref([])
const permissionTreeData = ref([])

const dialogTitle = computed(() => {
  return permissionForm.id ? '编辑权限' : '新增权限'
})

const permissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 模拟权限数据
const mockData = [
  {
    id: 1,
    name: '系统管理',
    code: 'system',
    type: 'menu',
    resource: '/system',
    method: '',
    description: '系统管理模块',
    status: 1,
    sort: 1,
    children: [
      {
        id: 11,
        name: '用户管理',
        code: 'system:user',
        type: 'menu',
        resource: '/system/user',
        method: '',
        description: '用户管理页面',
        status: 1,
        sort: 1,
        parentId: 1,
        children: [
          {
            id: 111,
            name: '新增用户',
            code: 'system:user:add',
            type: 'button',
            resource: '/api/users',
            method: 'POST',
            description: '新增用户按钮权限',
            status: 1,
            sort: 1,
            parentId: 11
          },
          {
            id: 112,
            name: '编辑用户',
            code: 'system:user:edit',
            type: 'button',
            resource: '/api/users/*',
            method: 'PUT',
            description: '编辑用户按钮权限',
            status: 1,
            sort: 2,
            parentId: 11
          },
          {
            id: 113,
            name: '删除用户',
            code: 'system:user:delete',
            type: 'button',
            resource: '/api/users/*',
            method: 'DELETE',
            description: '删除用户按钮权限',
            status: 1,
            sort: 3,
            parentId: 11
          }
        ]
      },
      {
        id: 12,
        name: '角色管理',
        code: 'system:role',
        type: 'menu',
        resource: '/system/role',
        method: '',
        description: '角色管理页面',
        status: 1,
        sort: 2,
        parentId: 1
      }
    ]
  }
]

const getTypeColor = (type) => {
  const colors = {
    menu: 'primary',
    button: 'success',
    data: 'warning'
  }
  return colors[type] || 'info'
}

const getTypeName = (type) => {
  const names = {
    menu: '菜单权限',
    button: '按钮权限',
    data: '数据权限'
  }
  return names[type] || '未知'
}

const getMethodColor = (method) => {
  const colors = {
    GET: 'success',
    POST: 'primary',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info'
  }
  return colors[method] || 'info'
}

const fetchData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockData
    permissionTreeData.value = [{ id: null, name: '顶级权限', children: mockData }]
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.type = ''
  handleSearch()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleAddChild = (row) => {
  resetForm()
  permissionForm.parentId = row.id
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(permissionForm, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个权限吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    console.log('取消删除')
  }
}

const handleStatusChange = async (row) => {
  try {
    ElMessage.success(`权限状态已${row.status ? '启用' : '禁用'}`)
  } catch (error) {
    ElMessage.error('状态切换失败')
    row.status = row.status ? 0 : 1
  }
}

const handleSubmit = async () => {
  if (!permissionFormRef.value) return
  
  try {
    const valid = await permissionFormRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(permissionForm.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  permissionForm.id = null
  permissionForm.parentId = null
  permissionForm.name = ''
  permissionForm.code = ''
  permissionForm.type = 'menu'
  permissionForm.resource = ''
  permissionForm.method = ''
  permissionForm.description = ''
  permissionForm.sort = 0
  if (permissionFormRef.value) {
    permissionFormRef.value.clearValidate()
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.permission-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 移动端卡片样式 */
.permission-card {
  .permission-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;

    .permission-info {
      flex: 1;

      h3 {
        margin: 0 0 4px 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      .permission-code {
        margin: 0;
        font-size: 14px;
        color: #666;
        font-family: monospace;
        background: #f5f5f5;
        padding: 2px 6px;
        border-radius: 3px;
        display: inline-block;
      }
    }

    .permission-tags {
      display: flex;
      flex-direction: column;
      gap: 4px;
      align-items: flex-end;
    }
  }

  .permission-details {
    margin-bottom: 12px;

    .detail-item {
      display: flex;
      margin-bottom: 6px;
      font-size: 14px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        color: #666;
        min-width: 80px;
      }

      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }
  }

  .permission-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
    flex-wrap: wrap;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .permission-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;

    .el-button {
      width: 100%;
    }
  }
}
</style>
